package com.yxh.service.impl;

import com.yxh.dao.UserMapper;
import com.yxh.pojo.MyTask;
import com.yxh.pojo.User;
import com.yxh.service.FlowManageService;
import com.yxh.service.ViciousService;
import com.yxh.util.DateJsonValueProcessor;
import com.yxh.util.PageBean;
import com.yxh.util.SnowflakeIdWorker;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.alibaba.druid.support.json.JSONUtils.toJSONString;

/**
 * Created by asus on 2018/6/26.
 */
@Service
@Transactional
public class FlowManageServiceImpl implements FlowManageService {

    @Autowired
    private  RuntimeService runtimeService;

    @Autowired
    private  TaskService taskService;

    @Autowired
    private ViciousService viciousService;

    @Autowired
    private UserMapper userMapper;

    @Override
    public void start(Map<String, Object> variables, String key, String user, String conment) {


        ProcessInstance pi =runtimeService.startProcessInstanceByKey(key,variables);

        Task task = taskService.createTaskQuery().processInstanceId(pi.getProcessInstanceId()).singleResult();
        String processInstacnId = task.getProcessInstanceId();
        Authentication.setAuthenticatedUserId(user);//
        taskService.addComment(task.getId(), processInstacnId, conment);
        taskService.complete(task.getId(),variables);

    }

    @Override
    public List<Task> taskList(String page, String pageSize, String id, String key) {

            PageBean pageBean = new PageBean();
            pageBean.setPage(Integer.parseInt(page));
            pageBean.setPageSize(Integer.parseInt(pageSize));


        //根据人员查询任务表单
        List<Task> taskList = taskService.createTaskQuery().taskCandidateUser(id).processDefinitionKeyLike("%"+key+"%").
                orderByTaskCreateTime().desc().listPage(pageBean.getStart(), pageBean.getPageSize());

        return taskList;
    }

    @Override
    public JSONObject changeData(List<MyTask> tasks, String key,String id) {

        long total = taskService.createTaskQuery().taskCandidateUser(id).processDefinitionKeyLike("%"+key+"%").count();
        JsonConfig jsonConfig = new JsonConfig();
        jsonConfig.registerJsonValueProcessor(java.util.Date.class, new DateJsonValueProcessor("yyyy-MM-dd HH:mm:ss"));
        JSONObject result = new JSONObject();
        JSONArray jsonArray = JSONArray.fromObject(tasks, jsonConfig);
        result.put("rows", toJSONString(jsonArray));
        result.put("total", total);
        return result;
    }

    @Override
    public void insertImgs(String imgs, String id) {
        String [] img=imgs.split(",");
        Map<String,Object> parm=new HashMap<String,Object>();
        parm.put("foreign_id",id);
        for(int le = 0; img.length > le; le++){
            parm.put("img_id", SnowflakeIdWorker.creatId());
            parm.put("url",img[le]);
            viciousService.insertImg(parm);
        }
    }

    @Override
    public void insertImgs(List<Map<String, Object>> imgs, String id) {
        Map<String,Object> parm=new HashMap<String,Object>();
        parm.put("foreign_id",id);

        for(Map<String,Object> m:imgs){
            parm.put("img_id", SnowflakeIdWorker.creatId());
            parm.put("url",m.get("url"));
            parm.put("name",m.get("name"));
            viciousService.insertImg(parm);

      }

    }

    @Override
    public void complete(String taskId, Map<String, Object> variables, String operation, String megs) {

        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        String processInstacnId = task.getProcessInstanceId();
        Authentication.setAuthenticatedUserId(operation);
        taskService.addComment(taskId, processInstacnId, megs);

        taskService.complete(taskId,variables);



    }

    @Override
    public String nameBack(String auditingId) {
        String auditingName = "";
        List<User> user=userMapper.seleectByIds(auditingId.split(","));
        for(User u:user){
            auditingName+=u.getUsername()+",";
        }

        return  auditingName.substring(0, auditingName.length()-1);

    }
}
